package com.yiren.dbaa.module.practice_set.device;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.CarSignalConfigBean;
import com.yiren.backstage.config.bean.device.PracticeCarCheckConfigBean;
import com.yiren.backstage.config.bean.device.SignalSourceConfigBean;
import com.yiren.backstage.config.enums.CarTypeEnum;
import com.yiren.backstage.config.enums.GearTypeEnum;
import com.yiren.backstage.config.enums.LocationTypeEnum;
import com.yiren.backstage.config.enums.RoverStationEnum;
import com.yiren.backstage.config.enums.SpeedTypeEnum;
import com.yiren.backstage.currency.bean.CarStateBean;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.entity.CarModelEntity;
import com.yiren.backstage.currency.enums.CarStateNameEnum;
import com.yiren.backstage.currency.enums.CarStateValueEnum;
import com.yiren.backstage.currency.utils.StringUtil;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.R;
import com.yiren.dbaa.constant.G;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.currency.event.SwitchOBDEvent;
import com.yiren.dbaa.currency.model.ObdCarModel;
import com.yiren.dbaa.module.device.contract.DeviceConfigContract;
import com.yiren.dbaa.module.device.contract.LowerComputerContract;
import com.yiren.dbaa.module.device.presenter.DeviceConfigPresenter;
import com.yiren.dbaa.module.device.view.activity.GYROStudyActivity;
import com.yiren.dbaa.module.device.view.activity.GearCorrectActivity;
import com.yiren.dbaa.module.device.view.activity.GearsZiyanActivity;
import com.yiren.dbaa.module.device.view.dialog.SelectObdModelDialog;
import com.yiren.dbaa.module.param_config.api.ParamConfigApi;
import com.yiren.dbaa.module.project_edit.view.adapter.SelectParamAdapter;
import com.yiren.dbaa.net.bean.WiringConfigBean;
import com.yiren.dbaa.util.DensityUtil;
import com.yiren.dbaa.view.adapter.WiringConfigAdapter;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lwb
 * on 2021/12/29
 * Describe  通用设置Fragment
 */
public class DeviceSetFragment extends Fragment implements DeviceConfigContract.View, LowerComputerContract.View, WiringConfigAdapter.OnSignalActionListener {

    @BindView(R.id.tv_car_model)
    TextView tvCarModel;
    @BindView(R.id.tv_car_model_gjd)
    TextView tvCarModelGjd;
    @BindView(R.id.tv_gear_type)
    TextView tvGearType;
    @BindView(R.id.tv_gear_cdb)
    TextView tvGearCdb;
    @BindView(R.id.tv_gjd_type)
    TextView tvGjdType;
    @BindView(R.id.tv_device_connect)
    TextView tvDeviceConnect;
    @BindView(R.id.tv_speed_type)
    TextView tvSpeedType;
    @BindView(R.id.tv_gps_type)
    TextView tvGpsType;
    @BindView(R.id.tv_car_type)
    TextView tvCarType;
    @BindView(R.id.et_speed_stable)
    EditText etSpeedStable;
    @BindView(R.id.et_qibu_dynamic)
    EditText etQibuDynamic;
    @BindView(R.id.tb_correct_speed)
    RelativeLayout tbCorrectSpeed;
    @BindView(R.id.tb_correct_rotate)
    RelativeLayout tbCorrectRotate;
    @BindView(R.id.et_correct_speed)
    EditText etCorrectSpeed;
    @BindView(R.id.et_correct_rotate)
    EditText etCorrectRotate;
    @BindView(R.id.tv_real_speed)
    TextView tvRealSpeed;
    @BindView(R.id.tv_real_rotate)
    TextView tvRealRotate;
    @BindView(R.id.bt_cdb_study)
    TextView btCdbStudy;
    @BindView(R.id.bt_gear_study)
    TextView btGearStudy;
    @BindView(R.id.lv_wiring_set)
    ListView lvWiringSet;

    @BindView(R.id.tv_state_xcd)
    TextView tvStateXcd;
    @BindView(R.id.cb_revise_xcd)
    CheckBox cbReviseXcd;
    @BindView(R.id.tv_state_zzd)
    TextView tvStateZzd;
    @BindView(R.id.cb_revise_zzd)
    CheckBox cbReviseZzd;
    @BindView(R.id.tv_state_wd)
    TextView tvStateWd;
    @BindView(R.id.cb_revise_wd)
    CheckBox cbReviseWd;
    @BindView(R.id.tv_state_js)
    TextView tvStateJs;
    @BindView(R.id.cb_revise_js)
    CheckBox cbReviseJs;
    @BindView(R.id.tv_state_aqd)
    TextView tvStateAqd;
    @BindView(R.id.cb_revise_aqd)
    CheckBox cbReviseAqd;
    @BindView(R.id.tv_state_jgd)
    TextView tvStateJgd;
    @BindView(R.id.cb_revise_jgd)
    CheckBox cbReviseJgd;
    @BindView(R.id.tv_state_yzd)
    TextView tvStateYzd;
    @BindView(R.id.cb_revise_yzd)
    CheckBox cbReviseYzd;
    @BindView(R.id.tv_state_lh)
    TextView tvStateLh;
    @BindView(R.id.cb_revise_lh)
    CheckBox cbReviseLh;
    @BindView(R.id.tv_state_cm)
    TextView tvStateCm;
    @BindView(R.id.cb_revise_cm)
    CheckBox cbReviseCm;
    @BindView(R.id.tv_state_ygd)
    TextView tvStateYgd;
    @BindView(R.id.cb_revise_ygd)
    CheckBox cbReviseYgd;
    @BindView(R.id.tv_state_jsd)
    TextView tvStateJsd;
    @BindView(R.id.cb_revise_jsd)
    CheckBox cbReviseJsd;
    @BindView(R.id.tv_state_ss)
    TextView tvStateSs;
    @BindView(R.id.cb_revise_ss)
    CheckBox cbReviseSs;
    @BindView(R.id.tv_state_lb)
    TextView tvStateLb;
    @BindView(R.id.cb_revise_lb)
    CheckBox cbReviseLb;

    @BindView(R.id.sv_device)
    ScrollView svDevice;

    private SignalSourceConfigBean signalSourceConfig;
    private PracticeCarCheckConfigBean practiceCarCheckConfig;
    private CarSignalConfigBean carSignalConfig;

    private GearTypeEnum[] gearTypes;
    private RoverStationEnum[] roverStations;
    private SpeedTypeEnum[] speedTypes;
    private LocationTypeEnum[] locationTypes;
    private CarTypeEnum[] carTypes;

    private List<String> selectList;

    //初始值
    private Handler handler;
    private Runnable runnable;
    private List<CarStateTextViewBean> carStateTextViewList;
    private List<CarModelEntity> carModelList;

    private DeviceConfigContract.Presenter deviceConfigPresenter;
    private WiringConfigAdapter wiringConfigAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_device_set, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        setData();
        initListener();
        refresh();
    }

    private void initData() {
        handler = new Handler();
        selectList = new ArrayList<String>();
        gearTypes = GearTypeEnum.values();
        roverStations = RoverStationEnum.values();
        speedTypes = SpeedTypeEnum.values();
        locationTypes = LocationTypeEnum.values();
        carTypes = CarTypeEnum.values();
        signalSourceConfig = LoadConfigApi.loadSignalSourceConfig(getActivity());
        practiceCarCheckConfig = LoadConfigApi.loadPracticeCarCheckConfig(getActivity());
        carSignalConfig = LoadConfigApi.loadCarSignalConfig(getActivity());
        carStateTextViewList = new ArrayList<>();
        deviceConfigPresenter = new DeviceConfigPresenter(getActivity());

        svDevice.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        svDevice.setFocusable(true);
        svDevice.setFocusableInTouchMode(true);
        svDevice.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.requestFocusFromTouch();
                return false;
            }
        });
    }

    /**
     * 设置控件数据
     */
    private void setData() {
        //车辆模型
        tvCarModel.setText(deviceConfigPresenter.getObdName());
        //档位类型
        tvGearType.setText(signalSourceConfig.getGearType().getDescription());
        //高精车模
        if (StringUtil.isEmpty(signalSourceConfig.getCarModelId())) {
            tvCarModelGjd.setText("未选择");
        } else {
            CarModelEntity carModel = (CarModelEntity) UserDbController.getInstance(false).queryById(signalSourceConfig.getCarModelId(), CarModelEntity.class);
            if (carModel == null) {
                tvCarModelGjd.setText("请先下载该车模");
            } else {
                tvCarModelGjd.setText(carModel.getName());
            }
        }

        //挡位学习是否显示
        if (signalSourceConfig.getGearType() == GearTypeEnum.ANGLE_WHOLE_GEAR || signalSourceConfig.getGearType() == GearTypeEnum.XY_MECHANICS_WHOLE_GEAR) {
            btGearStudy.setVisibility(View.VISIBLE);
        } else {
            btGearStudy.setVisibility(View.GONE);
        }

        //高精度移动站类型
        tvGjdType.setText(signalSourceConfig.getRoverStationType().getDescription());
        //车速获取方式
        tvSpeedType.setText(signalSourceConfig.getSpeedType().getDescription());
        //GPS类型
        tvGpsType.setText(signalSourceConfig.getLocationType().getDescription());
        //车辆类型
        tvCarType.setText(signalSourceConfig.getCarType().getDescription() + "车型");

        //制动不平顺灵敏度
        etSpeedStable.setText(practiceCarCheckConfig.getZdbpsValue() + "");
        //起步闯动灵敏度
        etQibuDynamic.setText(practiceCarCheckConfig.getQbcdValue() + "");

        //传动比检测档位
        if (practiceCarCheckConfig.isCdbCheckGear()) {
            btCdbStudy.setVisibility(View.VISIBLE);
            tvGearCdb.setText("是");
        } else {
            btCdbStudy.setVisibility(View.GONE);
            tvGearCdb.setText("否");
        }

        if (signalSourceConfig.isMpDevice()) {
            tbCorrectSpeed.setVisibility(View.GONE);
            tbCorrectRotate.setVisibility(View.GONE);
        }

        //转速车速修正值
        etCorrectRotate.setText(carSignalConfig.getMap().get(CarStateNameEnum.ROTATE_SPEED.toString()).toString());
        etCorrectSpeed.setText(carSignalConfig.getMap().get(CarStateNameEnum.SPEED.toString()).toString());
        //加载接线配置
        deviceConfigPresenter.loadWiringConfig(this);

        //编辑框监听
        etQibuDynamic.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                Pattern p = Pattern.compile("[0-9]*");
                Matcher m = p.matcher(etQibuDynamic.getText().toString());
                if (m.matches() && !StringUtil.isEmpty(etQibuDynamic.getText().toString())) {
                    practiceCarCheckConfig.setQbcdValue(Float.parseFloat(etQibuDynamic.getText().toString()));
                    ParamConfigApi.savePracticeCarCheckConfig(getActivity(), practiceCarCheckConfig);
                }
            }
        });
        etSpeedStable.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                Pattern p = Pattern.compile("[0-9]*");
                Matcher m = p.matcher(etSpeedStable.getText().toString());
                if (m.matches() && !StringUtil.isEmpty(etSpeedStable.getText().toString())) {
                    practiceCarCheckConfig.setZdbpsValue(Float.parseFloat(etSpeedStable.getText().toString()));
                    ParamConfigApi.savePracticeCarCheckConfig(getActivity(), practiceCarCheckConfig);
                }
            }
        });
        etCorrectSpeed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                Pattern p = Pattern.compile("[0-9]*");
                Matcher m = p.matcher(etCorrectSpeed.getText().toString());
                if (m.matches() && !StringUtil.isEmpty(etCorrectSpeed.getText().toString())) {
                    deviceConfigPresenter.saveCorrectNumber(etCorrectSpeed.getText().toString(), String.valueOf(carSignalConfig.getMap().get(CarStateNameEnum.ROTATE_SPEED.toString())));
                }
            }
        });
        etCorrectRotate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                Pattern p = Pattern.compile("[0-9]*");
                Matcher m = p.matcher(etCorrectRotate.getText().toString());
                if (m.matches() && !StringUtil.isEmpty(etCorrectRotate.getText().toString())) {
                    deviceConfigPresenter.saveCorrectNumber(String.valueOf(carSignalConfig.getMap().get(CarStateNameEnum.SPEED.toString())), etCorrectRotate.getText().toString());
                }
            }
        });
    }

    /**
     * 刷新车辆信号状态
     */
    private void refresh() {
        runnable = () -> {
            carStateTextViewList.clear();
            CarStateBean carStateBean = CarStateBean.getInstance();
            tvStateXcd.setText(carStateBean.getDrivingLamp().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateXcd, carStateBean.getDrivingLamp()));
            tvStateZzd.setText(carStateBean.getLeftLight().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateZzd, carStateBean.getLeftLight()));
            tvStateWd.setText(carStateBean.getFoglight().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateWd, carStateBean.getFoglight()));
            tvStateJs.setText(carStateBean.getFootBrake().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateJs, carStateBean.getFootBrake()));
            tvStateAqd.setText(carStateBean.getSafetyBelt().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateAqd, carStateBean.getSafetyBelt()));
            tvStateJgd.setText(carStateBean.getPassingLight().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateJgd, carStateBean.getPassingLight()));
            tvStateYzd.setText(carStateBean.getRightLight().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateYzd, carStateBean.getRightLight()));
            tvStateLh.setText(carStateBean.getSeparationReunion().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateLh, carStateBean.getSeparationReunion()));
            tvStateCm.setText(carStateBean.getCarDoor().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateCm, carStateBean.getCarDoor()));
            tvStateYgd.setText(carStateBean.getDistanceLight().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateYgd, carStateBean.getDistanceLight()));
            tvStateJsd.setText(carStateBean.getCautionLight().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateJsd, carStateBean.getCautionLight()));
            tvStateSs.setText(carStateBean.getParkingBrake().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateSs, carStateBean.getParkingBrake()));
            tvStateLb.setText(carStateBean.getHorn().getName());
            carStateTextViewList.add(new CarStateTextViewBean(tvStateLb, carStateBean.getHorn()));
            for (CarStateTextViewBean carStateTextView : carStateTextViewList) {
                CarStateValueEnum carStateValue = carStateTextView.getCarStateValueEnum();
                if (carStateValue.equals(CarStateValueEnum.LOOSEN) || carStateValue.equals(CarStateValueEnum.CLOSE) || carStateValue.equals(CarStateValueEnum.NO_PASS) || carStateValue.equals(CarStateValueEnum.NOT_ADJUST) || carStateValue.equals(CarStateValueEnum.NOT_TOUCH)) {
                    carStateTextView.getTv().setTextColor(Color.parseColor("#D9211E"));
                } else if (carStateValue.equals(CarStateValueEnum.NO_DETECT)) {
                } else {
                    carStateTextView.getTv().setTextColor(Color.parseColor("#22A146"));
                }
            }
            tvRealSpeed.setText("(实时车速:" + CarStateBean.getInstance().getSpeed() + "码)");
            tvRealRotate.setText("(实时转速:" + CarStateBean.getInstance().getRotateSpeed() + "转)");
            //是否蓝牙连接
            if (SignalGConstant.isOpen) {
                tvDeviceConnect.setText("蓝牙");
            } else {
                if (G.connectDeviceMessage != null) {
                    tvDeviceConnect.setText("串口");
                } else {
                    tvDeviceConnect.setText("未连接");
                }
            }
            handler.postDelayed(runnable, 1000);
        };
        handler.post(runnable);
    }

    @OnClick({R.id.iv_speed_stable_delete, R.id.iv_qibu_dynamic_delete, R.id.tv_gear_type, R.id.bt_cdb_study, R.id.tv_car_model_gjd, R.id.bt_gear_study, R.id.tv_gear_cdb, R.id.tv_device_connect_blue, R.id.tv_gjd_type, R.id.tv_speed_type, R.id.tv_gps_type, R.id.tv_car_type, R.id.tv_car_model,
            R.id.cb_revise_xcd, R.id.cb_revise_zzd, R.id.cb_revise_wd, R.id.cb_revise_js, R.id.cb_revise_jgd, R.id.cb_revise_yzd, R.id.cb_revise_lh,
            R.id.cb_revise_cm, R.id.cb_revise_ygd, R.id.cb_revise_jsd, R.id.cb_revise_ss, R.id.cb_revise_lb, R.id.cb_revise_aqd})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_speed_stable_delete:
                etSpeedStable.setText("");
                break;
            case R.id.iv_qibu_dynamic_delete:
                etQibuDynamic.setText("");
                break;
            case R.id.tv_car_model:
                getActivity().runOnUiThread(() -> LoadDialog.show(getActivity(), "正在切换车辆模型..."));
                deviceConfigPresenter.switchObd(this);
                break;
            case R.id.bt_cdb_study:
                getActivity().startActivity(new Intent(getActivity(), GearCorrectActivity.class));
                break;
            case R.id.tv_car_model_gjd:
                setDialogValues(6, "高精度车模", tvCarModelGjd);
                break;
            case R.id.bt_gear_study:
                if (signalSourceConfig.getGearType() == GearTypeEnum.ANGLE_WHOLE_GEAR) {
                    getActivity().startActivity(new Intent(getActivity(), GYROStudyActivity.class));
                } else if (signalSourceConfig.getGearType() == GearTypeEnum.XY_MECHANICS_WHOLE_GEAR) {
                    getActivity().startActivity(new Intent(getActivity(), GearsZiyanActivity.class));
                }
                break;
            case R.id.tv_device_connect_blue:
                getActivity().startActivity(new Intent(getActivity(), BlueToothActivity.class));
                break;
            case R.id.tv_gear_type:
                setDialogValues(1, getResources().getString(R.string.param_gear_type), tvGearType);
                break;
            case R.id.tv_gjd_type:
                setDialogValues(2, getResources().getString(R.string.param_gjd_type), tvGjdType);
                break;
            case R.id.tv_speed_type:
                setDialogValues(3, getResources().getString(R.string.param_speed_way), tvSpeedType);
                break;
            case R.id.tv_gps_type:
                setDialogValues(4, getResources().getString(R.string.param_gps_type), tvGpsType);
                break;
            case R.id.tv_car_type:
                setDialogValues(5, getResources().getString(R.string.param_car_type), tvCarType);
                break;
            case R.id.tv_gear_cdb:
                setDialogValues(7, "传动比档位", tvGearCdb);
                break;
            case R.id.cb_revise_xcd:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.DRIVING_LAMP.toString());
                break;
            case R.id.cb_revise_zzd:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.LEFT_LIGHT.toString());
                break;
            case R.id.cb_revise_wd:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.FOGLIGHT.toString());
                break;
            case R.id.cb_revise_js:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.FOOT_BRAKE.toString());
                break;
            case R.id.cb_revise_jgd:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.PASSING_LIGHT.toString());
                break;
            case R.id.cb_revise_yzd:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.RIGHT_LIGHT.toString());
                break;
            case R.id.cb_revise_lh:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.SEPARATION_REUNION.toString());
                break;
            case R.id.cb_revise_cm:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.CAR_DOOR.toString());
                break;
            case R.id.cb_revise_ygd:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.DISTANCE_LIGHT.toString());
                break;
            case R.id.cb_revise_jsd:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.CAUTION_LIGHT.toString());
                break;
            case R.id.cb_revise_ss:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.PARKING_BRAKE.toString());
                break;
            case R.id.cb_revise_lb:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.HORN.toString());
                break;
            case R.id.cb_revise_aqd:
                deviceConfigPresenter.setCarStateSignal(CarStateNameEnum.SAFETY_BELT.toString());
                break;
        }
    }

    private void initListener() {
        CarSignalConfigBean carSignalConfig = LoadConfigApi.loadCarSignalConfig(getActivity());
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.DRIVING_LAMP.toString()) == true) {
            cbReviseXcd.setChecked(true);
        } else {
            cbReviseXcd.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.LEFT_LIGHT.toString()) == true) {
            cbReviseZzd.setChecked(true);
        } else {
            cbReviseZzd.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.FOGLIGHT.toString()) == true) {
            cbReviseWd.setChecked(true);
        } else {
            cbReviseWd.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.FOOT_BRAKE.toString()) == true) {
            cbReviseJs.setChecked(true);
        } else {
            cbReviseJs.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.PASSING_LIGHT.toString()) == true) {
            cbReviseJgd.setChecked(true);
        } else {
            cbReviseJgd.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.RIGHT_LIGHT.toString()) == true) {
            cbReviseYzd.setChecked(true);
        } else {
            cbReviseYzd.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.SEPARATION_REUNION.toString()) == true) {
            cbReviseLh.setChecked(true);
        } else {
            cbReviseLh.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.CAR_DOOR.toString()) == true) {
            cbReviseCm.setChecked(true);
        } else {
            cbReviseCm.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.DISTANCE_LIGHT.toString()) == true) {
            cbReviseYgd.setChecked(true);
        } else {
            cbReviseYgd.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.CAUTION_LIGHT.toString()) == true) {
            cbReviseJsd.setChecked(true);
        } else {
            cbReviseJsd.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.PARKING_BRAKE.toString()) == true) {
            cbReviseSs.setChecked(true);
        } else {
            cbReviseSs.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.HORN.toString()) == true) {
            cbReviseLb.setChecked(true);
        } else {
            cbReviseLb.setChecked(false);
        }
        if (!(boolean) carSignalConfig.getMap().get(CarStateNameEnum.SAFETY_BELT.toString()) == true) {
            cbReviseAqd.setChecked(true);
        } else {
            cbReviseAqd.setChecked(false);
        }
    }

    /**
     * 设置对话框的值
     */
    private void setDialogValues(int type, String title, TextView tv) {
        selectList.clear();
        String selectString = tv.getText().toString();
        switch (type) {
            case 1:
                for (int i = 0; i < gearTypes.length; i++) {
                    selectList.add(gearTypes[i].getDescription());
                }
                break;
            case 2:
                for (int i = 0; i < roverStations.length; i++) {
                    selectList.add(roverStations[i].getDescription());
                }
                break;
            case 3:
                for (int i = 0; i < speedTypes.length; i++) {
                    selectList.add(speedTypes[i].getDescription());
                }
                break;
            case 4:
                for (int i = 0; i < locationTypes.length; i++) {
                    selectList.add(locationTypes[i].getDescription());
                }
                break;
            case 5:
                for (int i = 0; i < carTypes.length; i++) {
                    selectList.add(carTypes[i].getDescription());
                }
                break;
            case 6:
                carModelList = UserDbController.getInstance(false).queryAll(CarModelEntity.class);
                if (carModelList.size() == 0) {
                    MessageBox.show(getActivity(), "请先下载车模再选择!");
                    return;
                }
                for (int i = 0; i < carModelList.size(); i++) {
                    selectList.add(carModelList.get(i).getName());
                }
                break;
            case 7:
                selectList.add("是");
                selectList.add("否");
                break;
        }
        showSelectDialog(type, title, tv, selectString);
    }

    /**
     * 弹出框选择（type 1:档位 2：移动站 3：车速 4:gps 5:车型 6:高精车模）
     */
    public void showSelectDialog(int type, String title, TextView tv, String selectString) {
        Dialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.show();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = (DensityUtil.getScreenWidth(getContext()) * 7) / 10;
        params.height = (DensityUtil.getScreenHeight(getContext()) * 6) / 10;
        dialog.getWindow().setAttributes(params);
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_select_box);
        TextView tvTitle = (TextView) window.findViewById(R.id.tv_title);
        ListView lvList = (ListView) window.findViewById(R.id.lv_dialog_list);
        lvList.setDivider(null);// 去除listview的下划线
        tvTitle.setText(title);
        SelectParamAdapter adapter = new SelectParamAdapter(getActivity(), selectList, selectString);
        lvList.setAdapter(adapter);
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv.setText(selectList.get(position));
                switch (type) {
                    case 1:  //档位类型
                        signalSourceConfig.setGearType(gearTypes[position]);
                        if (gearTypes[position] == GearTypeEnum.ANGLE_WHOLE_GEAR || gearTypes[position] == GearTypeEnum.XY_MECHANICS_WHOLE_GEAR) {
                            btGearStudy.setVisibility(View.VISIBLE);
                        } else {
                            btGearStudy.setVisibility(View.GONE);
                        }
                        break;
                    case 2:  //高精度移动站类型
                        signalSourceConfig.setRoverStationType(roverStations[position]);
                        break;
                    case 3:  //车速获取方式
                        signalSourceConfig.setSpeedType(speedTypes[position]);
                        break;
                    case 4:  //GPS类型
                        signalSourceConfig.setLocationType(locationTypes[position]);
                        break;
                    case 5:  //车辆类型
                        signalSourceConfig.setCarType(carTypes[position]);
                        break;
                    case 6:  //高精车模
                        signalSourceConfig.setCarModelId(carModelList.get(position).getId());
                        break;
                    case 7:  //传动比
                        if (position == 0) {
                            practiceCarCheckConfig.setCdbCheckGear(true);
                            btCdbStudy.setVisibility(View.VISIBLE);
                        } else {
                            practiceCarCheckConfig.setCdbCheckGear(false);
                            btCdbStudy.setVisibility(View.GONE);
                        }
                        break;
                }
                dialog.dismiss();
                ParamConfigApi.saveSignalSourceConfig(getActivity(), signalSourceConfig);
                ParamConfigApi.savePracticeCarCheckConfig(getActivity(), practiceCarCheckConfig);
            }
        });
    }

    @Override
    public void showSelectObdCarModelDialog(List<ObdCarModel> obdCarModels) {
        SelectObdModelDialog dataDialog = new SelectObdModelDialog(getActivity(), obdCarModels, new CommonCallBack() {
            @Override
            public void success(Object result) {
                deviceConfigPresenter.switchObdCarModel((Integer) result);
            }
        });
        dataDialog.showDialog();
    }

    @Override
    public void selectCarModelSuccess(String carModelName) {
        //选择车辆模型成功
        tvCarModel.setText(carModelName);
    }

    @Override
    public void updateDeviceInfo() {
        EventBus.getDefault().post(new SwitchOBDEvent());
    }

    @Override
    public void showWiringConfigList(List<WiringConfigBean> wiringConfigList) {
        wiringConfigAdapter = new WiringConfigAdapter(getActivity(), wiringConfigList, this);
        lvWiringSet.setAdapter(wiringConfigAdapter);
    }

    @Override
    public void refreshAdapter() {
        wiringConfigAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSignalAction(int position) {
        deviceConfigPresenter.showSelectStartProject(position, this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

}